<template>
    <div class="p-4 flex flex-col h-full">

        <div class="flex items-center justify-between mb-4 mr-2">
            <div class="text-lg font-medium text-tx-regular">文件({{ pager.lists.length }})</div>
            <div class="flex items-center">
                <el-input
                    v-model="queryParams.keyword"
                    class="w-[240px]"
                    size="large"
                    placeholder="搜索"
                    :prefix-icon="Search"
                    @input="resetPaging"
                />
                <el-button
                    class="ml-3 h-9"
                    :icon="Refresh"
                    @click="resetPaging"
                >刷新</el-button>
                <el-button
                    type="primary"
                    class="ml-3 h-9"
                    :icon="Plus"
                    :disabled="know.power < permissionEnum.EDIT"
                    @click="emits('toRow', 'imports')"
                >导入文件</el-button>
            </div>
        </div>

        <el-table
            v-loading="pager.loading"
            :data="pager.lists"
            class="cursor-pointer"
            size="large"
            row-class-name="h-[70px]"
            style="height: 100%"
            @row-click="tableItemClick"
        >
            <el-table-column fixed label="名称" prop="name" min-width="200">
                <template #default="scope: { row: KnowArchiveListResponse }">
                    <div class="flex items-center">
                        <icon
                            v-if="scope.row.scene === 'link'"
                            name="el-icon-Link"
                            :size="22"
                            color="#409eff"
                        />
                        <icon
                            v-else-if="scope.row.scene === 'text'"
                            name="el-icon-Notebook"
                            :size="18"
                            color="#3470ff"
                        />
                        <el-image
                            v-else
                            class="w-[22px] h-[22px]"
                            :src="suffixUtil.findUnitIcon(scope.row.name)"
                        />
                        <div class="ml-2">{{ scope.row.name }}</div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="训练模式" prop="train_type" min-width="100">
                <template #default="scope: { row: KnowArchiveListResponse }">
                    {{ trainModeMap[scope.row.train_mode] || '-' }}
                </template>
            </el-table-column>
            <el-table-column label="数据总量" prop="train_total" min-width="100" />
            <el-table-column label="等待训练" prop="train_waits" min-width="100" />
            <el-table-column label="状态">
                <template #default="scope: { row: KnowArchiveListResponse }">
                    <div v-if="scope.row.train_mode === 'qa' && scope.row.qa_status !== 3" >
                        <el-tag v-if="scope.row.qa_status === 0" type="info">待拆分</el-tag>
                        <el-tag v-if="scope.row.qa_status === 1" type="primary">排队中</el-tag>
                        <el-tag v-if="scope.row.qa_status === 2" type="warning">拆分中</el-tag>
                        <el-tooltip
                            v-if="scope.row.qa_status === 4"
                            effect="dark"
                            placement="top-start"
                            :content="scope.row?.fail_reason || '-'"
                        >
                            <el-tag type="danger">拆分失败</el-tag>
                        </el-tooltip>
                    </div>
                    <div v-else>
                        <el-tag v-if="!scope.row.train_waits" type="success">已就绪</el-tag>
                        <el-tag v-else type="info">索引中</el-tag>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="创建/更新时间" min-width="120" >
                <template #default="scope: { row: KnowArchiveListResponse }">
                    <p>{{ scope.row.create_time }}</p>
                    <p>{{ scope.row.update_time }}</p>
                </template>
            </el-table-column>
            <el-table-column min-width="50">
                <template #default="{ $index }">
                    <el-dropdown @command="handleCommand">
                        <icon name="el-icon-MoreFilled" color="#999" />
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item :command="{'command': 'rename', 'index': $index}">
                                    <div class="flex items-center py-[2px]">
                                        <icon name="el-icon-Edit"/>
                                        <span class="ml-1">重命名</span>
                                    </div>
                                </el-dropdown-item>
                                <el-dropdown-item :command="{'command': 'merge', 'index': $index}" divided>
                                    <div class="flex items-center py-[2px]">
                                        <icon name="el-icon-Files" />
                                        <span class="ml-1">合并</span>
                                    </div>
                                </el-dropdown-item>
                                <el-dropdown-item :command="{'command': 'delete', 'index': $index}" divided>
                                    <div class="flex items-center py-[2px]">
                                        <icon name="el-icon-Delete" />
                                        <span class="ml-1">删除</span>
                                    </div>
                                </el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </template>
            </el-table-column>
        </el-table>

        <div class="flex justify-end my-4 mb-0">
            <paging
                v-model="pager"
                layout="total, sizes, prev, pager, next, jumper"
                @change="queryLists"
            />
        </div>

        <popup
            width="400px"
            title="重命名"
            :async-close="true"
            :loading="updateState.loading"
            :show="(updateState.command === 'rename')"
            @close="updateState.command = ''"
            @confirm="handleEvents('rename')"
        >
            <div class="p-4 pb-0">
                <el-form>
                    <el-form-item required>
                        <el-input v-model="updateState.name" placeholder="请输入文件名称" />
                    </el-form-item>
                </el-form>
            </div>
        </popup>

        <popup
            width="400px"
            title="合并文件"
            :async-close="true"
            :loading="updateState.loading"
            :show="(updateState.command === 'merge')"
            @close="updateState.command = ''"
            @confirm="handleEvents('merge')"
        >
            <div class="p-4 pb-0">
                <el-form>
                    <div class="mb-4">
                        <el-alert
                            title="把当前文件里的数据合并到指定文件中, 谨慎操作!"
                            type="warning"
                            show-icon
                            :closable="false"
                        />
                    </div>
                    <el-form-item required>
                        <el-input v-model="updateState.target" placeholder="目标文件编号" />
                    </el-form-item>
                </el-form>
            </div>
        </popup>
    </div>
</template>

<script setup lang="ts">
import { Search, Plus, Refresh } from '@element-plus/icons-vue'
import { permissionEnum } from '~/enums/app'
import suffixUtil from '~/utils/suffix'
import knowArchiveApi from '~/api/agent/know/archive'

const emits = defineEmits(['toRow'])
const props = withDefaults(
    defineProps<{
        know: KnowManageDetailResponse;
    }>(),
    {}
)

// 更新状态
const updateState = reactive({
    id: 0,       // 文件ID
    code: '',    // 文件编号
    name: '',    // 文件名称
    target: '',  // 目标文件
    command: '', // 操作指令
    loading: false
})

// 训练模式
const trainModeMap: Record<string, string> = {
    chunk: '直接分段',
    qa: '问答拆分'
}

// 查询参数
const queryParams = reactive({
    kb: props.know.code,
    keyword: ''
})

// 分页查询
const {
    pager,
    queryLists,
    resetPaging
} = usePaging({
    fetchFun: knowArchiveApi.lists,
    params: queryParams
})

/**
 * 跳转文件
 *
 * @param row
 * @author zero
 */
const tableItemClick = (row: any) => {
    emits('toRow', 'dataset', row.code)
}

/**
 * 操作事件
 *
 * @param event
 * @author zero
 */
const handleEvents = async (event: string) => {
    updateState.loading = true
    switch (event) {
        case 'rename':
            if (!updateState.name) {
                updateState.loading = false
                return feedback.msgError('请填写文件名称')
            }
            await knowArchiveApi.rename({
                id: updateState.id,
                name: updateState.name
            }).finally(() => {
                updateState.loading = false
            })

            updateState.command = ''
            feedback.msgSuccess('重命名成功')
            await resetPaging()
            end()
            start()
            break
        case 'merge':
            if (!updateState.target) {
                updateState.loading = false
                return feedback.msgError('请填写目标文件编号')
            }
            await knowArchiveApi.merge({
                source_fid: updateState.code,
                target_fid: updateState.target
            }).finally(() => {
                updateState.loading = false
            })

            updateState.command = ''
            feedback.msgSuccess('重命名成功')
            await resetPaging()
            end()
            start()
            break
    }
}

/**
 * 表格指令
 *
 * @param d
 * @author zero
 */
const handleCommand = async (d: any) => {
    const command: string = d.command
    const index: number = d.index
    const row = pager.lists[index]
    switch (command) {
        case 'rename':
            updateState.id = row.id
            updateState.name = row.name
            updateState.command = command
            updateState.loading = false
            break
        case 'merge':
            updateState.id = row.id
            updateState.code = row.code
            updateState.target = ''
            updateState.command = command
            updateState.loading = false
            break
        case 'delete':
            feedback.confirm('您确定要删除吗?')
                .then(async () => {
                    await knowArchiveApi.delete(row.code)
                    feedback.msgSuccess('删除成功')
                    await resetPaging()
                    end()
                    start()
                })
            break
    }
}

/**
 * 检测训练数据
 */
const checkWaitingData = async () => {
    const ids: string[] = []
    pager.lists.forEach(item => {
        if (item.train_mode === 'qa' && [0, 1, 2].includes(item.qa_status)) {
            ids.push(String(item.code))
        }
    })

    if (ids.length === 0) {
        end()
    } else {
        const lists = await knowArchiveApi.inspect(ids)
        pager.lists.map((item) => {
            const index = lists.findIndex((item1: any) => item.id === item1.id)
            if (index >= 0) {
                item.qa_status = lists[index].qa_status
                item.train_mode = lists[index].train_mode
                item.train_total = lists[index].train_total
                item.train_waits = lists[index].train_waits
                item.is_disable = lists[index].is_disable
                item.update_time = lists[index].update_time
            }
        })
    }
}

const { start, end } = usePolling(checkWaitingData, {
    time: 1000 * 30,
    key: 'archive'
})

onMounted(async () => {
    await queryLists()
    start()
})

onUnmounted(() => {
    end()
})
</script>
